package com.qf.fengmimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fengmimall.order.entity.OrderItem;
import com.qf.fengmimall.order.entity.Orders;
import com.qf.fengmimall.order.mapper.OrdersMapper;
import com.qf.fengmimall.order.service.IOrderItemService;
import com.qf.fengmimall.order.service.IOrdersService;
import com.qf.fengmimall.order.until.OrderNumCreate;
import com.qf.fengmimall.product.entity.Product;
import com.qf.fengmimall.product.entity.ProductSku;
import com.qf.fengmimall.product.entity.ShoppingCart;
import com.qf.fengmimall.product.mapper.ProductMapper;
import com.qf.fengmimall.product.service.IProductSkuService;
import com.qf.fengmimall.product.service.IShoppingCartService;
import com.qf.fengmimall.user.service.IUserAddrService;
import com.qf.fengmimall.user.service.IUsersService;
import com.qf.fengmimall.wexin.until.WxpayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author lx
 * @since 2023-02-16
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IProductSkuService productSkuService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private IUserAddrService userAddrService;
    @Autowired
    private IOrderItemService orderItemService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd mm:HH:ss");


    /**
     * 下单信息落库
     *
     * @param cids
     * @param orders
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> addOrder(String cids, Orders orders) throws Exception {
        String[] split = cids.split(",");
        List<String> cidsLists = Arrays.asList(split);

        //1. 查询用户购物车中的对应的商品套餐库存量是否还足够
        // 如果库存够，则继续下单流程；如果库存量不足，直接抛出异常;任何一个商品的库存不足都算失败
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(new QueryWrapper<ShoppingCart>().in("cart_id", cidsLists));
        List<String> skuIds = shoppingCarts.stream().map(ShoppingCart::getSkuId).collect(Collectors.toList());
        List<String> productIds = shoppingCarts.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());
        //查询productSku
        List<ProductSku> productSkus = productSkuService.list(new QueryWrapper<ProductSku>().in("sku_id", skuIds));
        Map<String, ProductSku> productSkuMap = productSkus.stream().collect(Collectors.toMap(ProductSku::getSkuId, o -> o));
        StringBuilder productName = new StringBuilder();
        int count = 1;
        for (ShoppingCart shoppingCart : shoppingCarts) {
            String skuId = shoppingCart.getSkuId();
            ProductSku productSku = productSkuMap.get(skuId);
            if (productSku.getStock() < 0) {
                throw new Exception(productSku.getSkuName() + "库存不足");
            }
            //获取产品名称
            productName.append(productSku.getSkuName() + " " + productSku.getUntitled());
            if (count < shoppingCarts.size()) {
                productName.append(",");
            }
            count++;
        }

        //2. 生成唯一的订单编号
        String orderCode = OrderNumCreate.randomOrderCode();
        orders.setOrderId(orderCode);
        //查询根据productIds查询购物车产品
        List<Product> productImgsBuyIds = productMapper.getProductImgsBuyIds(productIds);
        Map<String, Product> productMap = productImgsBuyIds.stream().collect(Collectors.toMap(Product::getProductId, t -> t));
        //3. 生成订单主表（orders表）中的数据

        String format = simpleDateFormat.format(new Date());
        Date date = simpleDateFormat.parse(format);
        orders.setCreateTime(date);
        orders.setUntitled(productName.toString());
        orders.setStatus("1");
        //订单落库
        save(orders);
        //4. 生成订单明细表的数据 （OrderItem表）
        // 购物车中有几条数据，订单明细表中就有几条数据
        List<OrderItem> orderItems = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderItem orderItem = new OrderItem();
            String skuId = shoppingCart.getSkuId();
            String productId = shoppingCart.getProductId();
            ProductSku productSku = productSkuMap.get(skuId);
            Product product = productMap.get(productId);
            orderItem.setItemId(OrderNumCreate.randomOrderCode());
            orderItem.setOrderId(orderCode);
            orderItem.setSkuId(skuId);
            orderItem.setProductId(shoppingCart.getProductId());
            orderItem.setProductName(product.getProductName());
            orderItem.setProductImg(product.getImgs().get(0).getUrl());
            orderItem.setSkuName(productSku.getSkuName());
            orderItem.setProductPrice(BigDecimal.valueOf(productSku.getSellPrice()));
            orderItem.setBuyCounts(Integer.parseInt(shoppingCart.getCartNum()));
            orderItem.setTotalAmount(BigDecimal.valueOf(productSku.getSellPrice()).multiply(BigDecimal.valueOf(Long.parseLong(shoppingCart.getCartNum()))));
            orderItem.setBasketDate(simpleDateFormat.parse(shoppingCart.getCartTime()));
            orderItem.setBuyTime(orders.getCreateTime());
            orderItem.setIsComment(0);
            orderItems.add(orderItem);
        }
        //订单详情落库
        orderItemService.saveBatch(orderItems);
        //5. 删除用户购物车中的cids对应数据
        List<Integer> shoppingCartIds = shoppingCarts.stream().map(ShoppingCart::getCartId).collect(Collectors.toList());
        shoppingCartService.removeBatchByIds(shoppingCartIds);
        //6. 跟微信支付平台交互，获取可以支付的url
        String payUrl = WxpayUtils.getPayUrl(orderCode);
        //7. 组织返回的map数据
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderCode);
        map.put("productNames", productName);
        map.put("payUrl", payUrl);
        return map;
    }

    /**
     * 接受微信返回的支付状态
     *
     * @param oid
     * @return
     */

    @Override
    public String status(String oid) throws Exception {
        String tip = WxpayUtils.queryOrder(oid);
        if (tip.equals("SUCCESS")) {
            //更新订单状态,下单时间,更新时间，付款时间
            String date = simpleDateFormat.format(new Date());
            update(new UpdateWrapper<Orders>().set("pay_time", date));
            update(new UpdateWrapper<Orders>().set("status", "2"));
            update(new UpdateWrapper<Orders>().set("update_time", date));
            update(new UpdateWrapper<Orders>().set("pay_time", date));
            return "2";
        } else {
            return "-1";
        }
    }
}
